import { onMounted, onUnmounted, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useRouteStore } from '@/stores/route'
import { 
  routeObserverManager, 
  createRouteObserver 
} from '@/utils/router-observer'

/**
 * 路由观察者组合式函数
 * 提供便捷的观察者模式接口
 */
export function useRouteObserver() {
  const router = useRouter()
  const route = useRoute()
  const routeStore = useRouteStore()
  
  const observers = ref([])
  const isInitialized = ref(false)

  // 初始化路由观察者管理器
  const initObserver = () => {
    if (!isInitialized.value) {
      routeObserverManager.init(router)
      isInitialized.value = true
    }
  }

  // 添加观察者
  const addObserver = (observer) => {
    routeObserverManager.addObserver(observer)
    observers.value.push(observer)
  }

  // 移除观察者
  const removeObserver = (observer) => {
    routeObserverManager.removeObserver(observer)
    const index = observers.value.indexOf(observer)
    if (index > -1) {
      observers.value.splice(index, 1)
    }
  }

  // 清理所有观察者
  const cleanup = () => {
    observers.value.forEach(observer => {
      routeObserverManager.removeObserver(observer)
    })
    observers.value = []
  }

  // 预设的观察者配置
  const setupDefaultObservers = () => {
    // 页面标题观察者
    const titleObserver = createRouteObserver.pageTitle()
    addObserver(titleObserver)

    // 面包屑观察者
    const breadcrumbObserver = createRouteObserver.breadcrumb((breadcrumbs) => {
      routeStore.updateBreadcrumbs(breadcrumbs)
    })
    addObserver(breadcrumbObserver)

    // 用户状态观察者
    const userStateObserver = createRouteObserver.userState(routeStore)
    addObserver(userStateObserver)

    // 缓存管理观察者
    const cacheObserver = createRouteObserver.cache()
    addObserver(cacheObserver)

    // 路由状态同步观察者
    const routeStateObserver = createRouteObserver.custom((routeInfo) => {
      routeStore.updateCurrentRoute(routeInfo)
    })
    addObserver(routeStateObserver)
  }

  // 添加自定义导航观察者
  const addNavigationObserver = (name, callback) => {
    const observer = createRouteObserver.navigation(name, callback)
    addObserver(observer)
    return observer
  }

  // 添加自定义观察者
  const addCustomObserver = (updateFn) => {
    const observer = createRouteObserver.custom(updateFn)
    addObserver(observer)
    return observer
  }

  // 获取当前路由信息
  const getCurrentRoute = () => {
    return routeObserverManager.getCurrentRoute()
  }

  // 获取路由历史
  const getRouteHistory = () => {
    return routeObserverManager.getRouteHistory()
  }

  // 手动触发观察者更新
  const triggerUpdate = (routeInfo) => {
    routeObserverManager.triggerUpdate(routeInfo)
  }

  // 生命周期钩子
  onMounted(() => {
    initObserver()
  })

  onUnmounted(() => {
    cleanup()
  })

  return {
    // 状态
    observers,
    isInitialized,

    // 基础方法
    initObserver,
    addObserver,
    removeObserver,
    cleanup,

    // 便捷方法
    setupDefaultObservers,
    addNavigationObserver,
    addCustomObserver,

    // 信息获取
    getCurrentRoute,
    getRouteHistory,
    triggerUpdate,

    // 观察者工厂
    createObserver: createRouteObserver
  }
}

/**
 * 页面级别的路由观察者
 * 用于单个页面的路由监听
 */
export function usePageRouteObserver(pageName, options = {}) {
  const {
    onEnter = null,
    onLeave = null,
    onUpdate = null,
    enableLogging = true
  } = options

  const { addNavigationObserver, removeObserver } = useRouteObserver()
  
  let observer = null

  onMounted(() => {
    observer = addNavigationObserver(pageName, (routeInfo) => {
      if (enableLogging) {
        console.log(`[${pageName}] Route update:`, routeInfo)
      }

      // 页面进入
      if (onEnter && !routeInfo.from) {
        onEnter(routeInfo)
      }

      // 页面离开
      if (onLeave && routeInfo.from) {
        onLeave(routeInfo.from, routeInfo)
      }

      // 路由更新
      if (onUpdate) {
        onUpdate(routeInfo)
      }
    })
  })

  onUnmounted(() => {
    if (observer) {
      removeObserver(observer)
    }
  })

  return {
    observer
  }
}

/**
 * 路由权限守卫观察者
 */
export function useRouteGuard() {
  const routeStore = useRouteStore()
  const router = useRouter()
  const { addCustomObserver } = useRouteObserver()

  const setupAuthGuard = () => {
    const authObserver = addCustomObserver((routeInfo) => {
      const publicRoutes = ['/', '/about']
      
      if (!publicRoutes.includes(routeInfo.path)) {
        const token = localStorage.getItem('token') || sessionStorage.getItem('token')
        
        if (!token) {
          console.log('Unauthorized access, redirecting to login')
          routeStore.setRedirectPath(routeInfo.path)
          router.push('/')
        } else {
          routeStore.setAuthenticated(true)
        }
      }
    })

    return authObserver
  }

  const setupRoleGuard = (requiredRoles = []) => {
    const roleObserver = addCustomObserver((routeInfo) => {
      if (routeInfo.meta?.requiresRole) {
        const userRoles = routeStore.userInfo.roles || []
        const hasPermission = requiredRoles.some(role => userRoles.includes(role))
        
        if (!hasPermission) {
          console.log('Insufficient permissions')
          router.push('/unauthorized')
        }
      }
    })

    return roleObserver
  }

  return {
    setupAuthGuard,
    setupRoleGuard
  }
}

/**
 * 路由性能监控观察者
 */
export function useRoutePerformance() {
  const performanceData = ref({
    navigationTimes: {},
    slowRoutes: [],
    averageLoadTime: 0
  })

  const { addCustomObserver } = useRouteObserver()

  const setupPerformanceMonitoring = () => {
    let navigationStart = null

    const performanceObserver = addCustomObserver((routeInfo) => {
      const now = Date.now()
      
      if (navigationStart) {
        const loadTime = now - navigationStart
        const routePath = routeInfo.path
        
        // 记录导航时间
        if (!performanceData.value.navigationTimes[routePath]) {
          performanceData.value.navigationTimes[routePath] = []
        }
        performanceData.value.navigationTimes[routePath].push(loadTime)
        
        // 标记慢速路由（超过2秒）
        if (loadTime > 2000) {
          performanceData.value.slowRoutes.push({
            path: routePath,
            loadTime,
            timestamp: now
          })
        }
        
        // 计算平均加载时间
        const allTimes = Object.values(performanceData.value.navigationTimes).flat()
        performanceData.value.averageLoadTime = allTimes.reduce((a, b) => a + b, 0) / allTimes.length
        
        console.log(`[Performance] Route ${routePath} loaded in ${loadTime}ms`)
      }
      
      navigationStart = now
    })

    return performanceObserver
  }

  const getPerformanceReport = () => {
    return performanceData.value
  }

  const clearPerformanceData = () => {
    performanceData.value = {
      navigationTimes: {},
      slowRoutes: [],
      averageLoadTime: 0
    }
  }

  return {
    performanceData,
    setupPerformanceMonitoring,
    getPerformanceReport,
    clearPerformanceData
  }
}